import UQRCode from 'uqrcodejs';

export const useH5Qrcode = (canvasId: string) => {
  const drawQrcodeToCanvas = (
    modules: { isBlack: boolean }[][],
    context: UniApp.CanvasContext,
    componentInstance: any,
  ) => {
    return new Promise<string>((resolve, reject) => {
      context.clearRect(0, 0, 300, 300);

      const item_h = 300 / modules.length;
      const item_w = 300 / modules[0].length;
      context.setFillStyle('black')
      for (let i = 0; i < modules.length; i++) {
        for (let j = 0; j < modules[i].length; j++) {
          if (modules[i][j].isBlack) {
            // Canvas坐标：x是横坐标(列j)，y是纵坐标(行i)
            context.fillRect(j * item_w, i * item_h, item_w, item_h);
          }
        }
      }

      context.draw(true, () => {
        uni.canvasToTempFilePath(
          {
            canvasId,
            success: (res) => {
              resolve(res.tempFilePath);
            },
            fail: (err) => {
              reject(err);
            },
          },
          componentInstance,
        );
      })
    });
  }

  const getH5Qrcode = async (pageUrl: string, params?: Record<string, any>) => {
    const c_preffix = import.meta.env.VITE_WEB_SHARE_URL_PREFIX;
    const has_http = pageUrl.startsWith('http')

    const paramsString = params
      ? `?${Object.entries(params)
        .map(([key, value]) => `${key}=${value}`)
        .join('&')}`
      : ''

    const url = has_http
      ? pageUrl
      : `${c_preffix}#${String(pageUrl).startsWith('/') ? '' : '/'}${pageUrl}${paramsString}`;

    // return await toDataURL(url);
    const qr = new UQRCode();
    qr.data = url; // 设置实际的URL，而不是字符串 "uQRCode"
    qr.make();
    const modules = qr.modules;

    const instance = getCurrentInstance();
    const context = uni.createCanvasContext(canvasId, instance?.proxy);

    /**
     * 约定绘制板是 300 * 300 的，
     * 给定一个modules: { isBlack: boolean }[][]，绘制到canvas上
     */
    const qrcodeUrl = await drawQrcodeToCanvas(modules, context, instance);
    return { qrcodeUrl, path: url };
  }

  return {
    getH5Qrcode,
  };
}
